const parser = require('@babel/parser')
const traverse = require('@babel/traverse').default
const { transformFromAst } = require('@babel/core')
const fs = require('fs')
const path = require('path')

module.exports = {
  getAst(filename) {
    const content = fs.readFileSync(filename, 'utf-8')
    const ast =  parser.parse(content, {
      sourceType: 'module' //文件依赖如果是通过import引入，则配置为module
    })
    return ast
  },
  getDependencies(ast, filename) {
    let dependencies = {}
    traverse(ast, {
      ImportDeclaration({ node }) {
        let dependencyKey = node.source.value
        let fullFilePath =  './' + path.join(path.dirname(filename), dependencyKey).replace(/\\/g, '/')
        dependencies[dependencyKey] = fullFilePath
      }
    })

    return dependencies
  },
  getCode(ast) {
    const { code } = transformFromAst(ast, null, {
      presets: [
        '@babel/preset-env'
      ]
    })

    return code
  }
}